package com.zihao.solon_study.Gateway.Filters;

import org.noear.solon.annotation.Component;
import org.noear.solon.core.exception.StatusException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.core.handle.Result;

/**
 * 全局过滤器
 *
 */
@Component
public class GlobalListenerFilters implements Filter {
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        Long startTime = System.currentTimeMillis();

        try {
            chain.doFilter(ctx);
        } catch (StatusException e) {
            // TODO 这里无法接收到AuthException异常
            ctx.render(Result.failure(e.getCode(), e.getMessage()));
        } catch (Throwable e) {
            e.printStackTrace();
            ctx.render(Result.failure(500, e.getMessage()));
        }

        Long endTime = System.currentTimeMillis();
        System.out.println("请求路径：" + ctx.path()
                + ",用时：" + (endTime - startTime) + "ms"
                + ",状态：" + ctx.status());
    }
}